package ljl.alg.wangzheng_camp.round1.bfsdfs;

/**
 * 这个可太简单了，弱智都会做
 *
 * */
public class _79_search_words {
    
    /**
     * “你勉强算个高级” 一个秃顶说。
     * */
    public boolean exist(char[][] board, String word) {
        int m = board.length, n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (search(word, board, i, j, 0)) return true;
            }
        }
        return false;
    }
    
    boolean search(String word, char[][] board, int i, int j, int wordIndex) {
        if (wordIndex == word.length()) return true;
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || word.charAt(wordIndex) != board[i][j])
            return false;
        char c = board[i][j];
        board[i][j] = 0;
        boolean found = search(word, board, i + 1, j, wordIndex + 1) ||
            search(word, board, i, j + 1, wordIndex + 1) ||
            search(word, board, i - 1, j, wordIndex + 1) ||
            search(word, board, i, j - 1, wordIndex + 1);
        board[i][j] = c;
        return found;
    }
    
}
